/**
 * Mock Tool Manager Service
 * 端口: 4001
 * 模拟工具管理器，用于测试
 */

const express = require('express');
const app = express();
app.use(express.json());

const PORT = 4001;

/**
 * 模拟工具列表
 */
const mockTools = [
  {
    name: 'web_search',
    description: 'Search the web for information',
    parameters: {
      type: 'object',
      properties: {
        query: {
          type: 'string',
          description: 'The search query'
        }
      },
      required: ['query']
    }
  },
  {
    name: 'calculator',
    description: 'Perform mathematical calculations',
    parameters: {
      type: 'object',
      properties: {
        expression: {
          type: 'string',
          description: 'The mathematical expression to evaluate'
        }
      },
      required: ['expression']
    }
  },
  {
    name: 'get_current_time',
    description: 'Get the current date and time',
    parameters: {
      type: 'object',
      properties: {
        timezone: {
          type: 'string',
          description: 'The timezone (e.g., UTC, America/New_York)'
        }
      }
    }
  }
];

/**
 * 获取可用工具
 * POST /tools/get
 */
app.post('/tools/get', (req, res) => {
  const { sessionId, agentId, filters = {} } = req.body;

  console.log(`[ToolManager] Getting tools for session: ${sessionId}`);

  // 应用过滤器
  let tools = [...mockTools];
  if (filters.enabled === false) {
    tools = [];
  }

  res.json({
    sessionId,
    tools
  });
});

/**
 * 执行工具
 * POST /tools/execute
 */
app.post('/tools/execute', (req, res) => {
  const { sessionId, agentId, toolCall, timeout = 30000 } = req.body;

  const startTime = Date.now();
  const { id, function: func } = toolCall;
  const toolName = func.name;
  const args = JSON.parse(func.arguments || '{}');

  console.log(`[ToolManager] Executing tool: ${toolName}`);
  console.log(`  Session: ${sessionId}`);
  console.log(`  Arguments:`, args);

  // 模拟工具执行结果
  let result = '';
  let error = null;

  try {
    switch (toolName) {
      case 'web_search':
        result = `Found 5 results for "${args.query}":\n1. Spring AI Documentation\n2. Spring Boot Best Practices\n3. Agent Platform Architecture\n4. LLM Integration Guide\n5. Testing Strategies`;
        break;

      case 'calculator':
        try {
          // 简单的计算器（仅支持基本运算）
          const expr = args.expression.replace(/[^0-9+\-*/().]/g, '');
          result = `The result of ${args.expression} is: ${eval(expr)}`;
        } catch (e) {
          error = `Invalid expression: ${args.expression}`;
        }
        break;

      case 'get_current_time':
        const timezone = args.timezone || 'UTC';
        const now = new Date();
        result = `Current time in ${timezone}: ${now.toISOString()}`;
        break;

      default:
        error = `Unknown tool: ${toolName}`;
    }
  } catch (e) {
    error = e.message;
  }

  const executionTime = Date.now() - startTime;

  res.json({
    result: {
      id,
      result: error ? null : result,
      error
    },
    executionTime
  });
});

/**
 * 健康检查
 * GET /health
 */
app.get('/health', (req, res) => {
  res.json({
    status: 'ok',
    service: 'mock-tool-manager',
    port: PORT,
    availableTools: mockTools.length
  });
});

/**
 * 获取工具列表（调试）
 * GET /debug/tools
 */
app.get('/debug/tools', (req, res) => {
  res.json({
    tools: mockTools,
    count: mockTools.length
  });
});

// 启动服务
app.listen(PORT, () => {
  console.log('================================================');
  console.log('🛠️  Mock Tool Manager Service');
  console.log(`📡 Port: ${PORT}`);
  console.log(`🔗 URL: http://localhost:${PORT}`);
  console.log('================================================');
  console.log('');
  console.log('Available endpoints:');
  console.log('  POST /tools/get      - Get available tools');
  console.log('  POST /tools/execute  - Execute a tool');
  console.log('  GET  /health         - Health check');
  console.log('  GET  /debug/tools    - Debug view');
  console.log('');
  console.log(`Available tools: ${mockTools.length}`);
  mockTools.forEach(tool => {
    console.log(`  - ${tool.name}: ${tool.description}`);
  });
  console.log('');
});

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('\n[ToolManager] Shutting down gracefully...');
  process.exit(0);
});
